<template>
    <!--地图挂载dom-->
    <div id="map">
        <div class="MapTool">
            <el-select v-model="value" placeholder="请选择" @change="wmsChange">
                <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
            </el-select>
        </div>
        <div id="map-legend"><img id="legend"/></div>
        <div id="info">&nbsp;</div>
    </div>
</template>

<script>
    //引入依赖
    import {Map, View} from 'ol'
    import {OSM, ImageWMS, TileWMS} from 'ol/source';
    import {Tile as TileLayer, Image as ImageLayer} from 'ol/layer';

    let layer = null;
    export default {
        name: 'WMS',
        data() {
            return {
                options: [{
                    value: 'image',
                    label: '图片'
                }, {
                    value: 'tile',
                    label: '切片'
                }, {
                    value: 'legend',
                    label: '图例'
                }, {
                    value: 'feature',
                    label: '特征'
                }],
                value: ''
            }
        },
        mounted() {
            //初始化地图
            this.map = new Map({
                target: 'map',//指定挂载dom，注意必须是id
                layers: [
                    new TileLayer({
                        source: new OSM()//加载OpenStreetMap
                    })
                ],
                //配置视图
                view: new View({
                    projection: 'EPSG:4326',
                    center: [-74.047185, 40.679648],
                    zoom: 4  //缩放到的级别
                })
            });
        },
        methods: {
            wmsChange(type) {
                this.map.removeLayer(layer);
                switch (type) {
                    case "image":
                        layer = this.image()
                        break;
                    case "tile":
                        layer = this.tile()
                        break;
                    case "legend":
                        layer = this.legend();
                        break;
                    case "feature":
                        layer = this.feature();
                        break;

                }
                this.map.addLayer(layer)
                let bounds = [-74.047185, 40.679648,
                    -73.90782, 40.882078];
                this.map.getView().fit(bounds, this.map.getSize());
            },
            image() {
                //使用image与imageWMS加载wms地图服务
                return new ImageLayer({
                    source: new ImageWMS({
                        url: 'http://localhost:8080/geoserver/tiger/wms',
                        params: {
                            'FORMAT': 'image/png',
                            'VERSION': '1.1.1',
                            "STYLES": '',
                            "LAYERS": 'tiger:poly_landmarks',
                            "exceptions": 'application/vnd.ogc.se_inimage',
                        }
                    }),
                })
            },
            tile() {
                //使用tile瓦片方式返回地图数据
                return new TileLayer({
                    source: new TileWMS({
                        url: 'http://localhost:8080/geoserver/tiger/wms',
                        params: {'FORMAT':  'image/png',
                            'VERSION': '1.1.1',
                            'tiled': true,
                            "STYLES": '',
                            "LAYERS": 'tiger:poly_landmarks',
                            "exceptions": 'application/vnd.ogc.se_inimage',
                            'tilesOrigin': -74.047185 + "," + 40.679648
                        }
                    })
                })
            },
            legend() {
                //获取到地图的图例
                let layer = new ImageWMS({
                    url: 'http://localhost:8080/geoserver/tiger/wms',
                    params: {
                        'FORMAT': 'image/png',
                        'VERSION': '1.1.1',
                        "STYLES": '',
                        "LAYERS": 'tiger:poly_landmarks',
                        "exceptions": 'application/vnd.ogc.se_inimage',
                    }
                });
                const updateLegend = function (resolution) {
                    const graphicUrl = layer.getLegendUrl(resolution);
                    const img = document.getElementById('legend');
                    img.src = graphicUrl;
                };
                // Initial legend
                const resolution = this.map.getView().getResolution();
                updateLegend(resolution);

                // Update the legend when the resolution changes
                this.map.getView().on('change:resolution', function (event) {
                    const resolution = event.target.getResolution();
                    updateLegend(resolution);
                });
                return layer;
            },
            feature() {
                //获取到地图上的要素信息
                const wmsSource = new ImageWMS({
                    url: 'http://localhost:8080/geoserver/tiger/wms',
                    params: {
                        'FORMAT': 'image/png',
                        'VERSION': '1.1.1',
                        "STYLES": '',
                        "LAYERS": 'tiger:poly_landmarks',
                        "exceptions": 'application/vnd.ogc.se_inimage',
                    }
                });

                const wmsLayer = new ImageLayer({
                    source: wmsSource,
                });
                this.map.on('singleclick', (evt) => {
                    document.getElementById('info').innerHTML = '';
                    const viewResolution = /** @type {number} */ (this.map.getView().getResolution());
                    const url = wmsSource.getFeatureInfoUrl(
                        evt.coordinate,
                        viewResolution,
                        'EPSG:4326',
                        {'INFO_FORMAT': 'text/html'}
                    );
                    if (url) {
                        fetch(url)
                            .then((response) => response.text())
                            .then((html) => {
                                document.getElementById('info').innerHTML = html;
                            });
                    }
                });
                return wmsLayer;
            }


        }
    }
</script>

<style scoped>
    #map {
        width: 100%;
        height: 100%;
    }

    .MapTool {
        position: absolute;
        top: .5em;
        right: .5em;
        z-index: 9999;
    }

    #map-legend {
        position: absolute;
        bottom: .25em;
        right: .5em;
        z-index: 9999;
    }

    #info {
        position: absolute;
        bottom: .25em;
        z-index: 9999;
    }
</style>
